<template>
  <view class="container">
    <view style="height: 4rpx;"></view>
    <view class="pay" v-if="orderState">
      <view class="pay-title__box">
        <view class="pay-title">请在</view>
        <u-count-down autoStart millisecond format="mm:ss" @finish="finish" @change="onChange" :time="countDown">
          <view class="time">
            <text class="time__item">{{ timeData.minutes }}分</text>
            <text class="time__item">{{ timeData.seconds }}秒</text>
          </view>
        </u-count-down>
        <view class="pay-title">内完成支付，过时订单将会取消。</view>
      </view>
      <view class="pay-btn">
        <view class="pay-btn__cancel" @click.stop="delModal = true">
          取消订单
        </view>
        <view class="pay-btn__toPay" @click.stop="clickPay()">
          去支付
        </view>
      </view>
    </view>
    <view class="card">
      <callup-or-navigation :currCompa="currCompa" />
    </view>
    <view class="card" v-if="isAllRefund">
      <view class="refund">订单已全部退款</view>
      <!-- <view class="name">订单总价：</view> -->
      <!-- <view class="value">{{ totalPrices | moneyShow }} 元</view> -->
    </view>
    <!-- 1和4订单类型 -->
    <order-item :orderDeta='orderDeta.noAddress' />
    <order-info :orderInfo='noAddressOrder' />
    <!-- <order-item :orderDeta='orderDeta.noAddress' /> -->
    <!-- <order-info :orderInfo='noAddressOrder' /> -->
    <!-- 3和5订单类型 -->
    <order-item :orderDeta='orderDeta.haveAnAdd' />
    <order-info :orderInfo='haveAnAddOrder' />


    <view class="card total-prices">
      <view class="name">订单总价：</view>
      <view class="value">{{ totalPrices | moneyShow }} 元</view>
    </view>
    <view class="couponList-bottom" v-if="!orderState">
      <view class="couponList-bottom__btn" @click="goBack">返 回</view>
      <view class="couponList-bottom__btn" @click="goShop">去商城</view>
    </view>
    <view style="height:40rpx;"></view>
    <u-modal title="物流信息" :show="showModal" confirmColor="#de4141" @confirm="showModal = false">
      <view class="slot-content">
        <view class="logistics_box">
          <u-steps current="1" direction="column" activeColor="#de4141">
            <!-- :type="index === 0 ? 'primary' : ''" -->
            <u-steps-item :key="index" :title="item.state" :desc="item.date + ' - ' + item.time"
              v-for="(item, index) in logisticsInfo">
            </u-steps-item>
          </u-steps>
        </view>
      </view>
    </u-modal>
    <u-modal :show="delModal" showCancelButton confirmColor="#de4141" @cancel="delModal = false" @confirm="callDeleteApi"
      title="您确定要取消该订单吗?"></u-modal>
  </view>
</template>

<script>
import { mapState, mapMutations, } from 'vuex'
import {
  userPayApi,
  fastPieceApi,
  groupMyGoodsDelApi,
  goodsOrderDetailApi,
  getShopTypeCateListApi
} from '@/API/Shop'
import OrderItem from '@/Shop/components/OrderItem'
import OrderInfo from '@/Shop/components/OrderInfo'
import CallupOrNavigation from '@/Shop/components/CallupOrNavigation'
export default {
  name: 'OrderDetail',
  components: { OrderItem, OrderInfo, CallupOrNavigation },
  data() {
    return {
      timeData: {},
      delModal: false,
      showModal: false,
      logisticsInfo: [],
      PostInfo: {},
      // queryParam: {
      //   uuid: '',
      //   v_id: ''
      // },
      baseUrl: this.$baseUrl,
      goodsOrderDeta: []
    }
  },
  computed: {
    ...mapState(['centers', 'brandInfo', 'loginInfo',]),
    // 公司信息
    firstOrder() {
      return this.goodsOrderDeta?.[0] || {}
    },
    totalPrices() {
      return this.firstOrder?.price_paid || 0
    },
    // 公司信息
    currCompa() {
      let centers = this.centers
      let id = this.firstOrder?.company_id
      if (!id) return {}
      let temp = centers.find(item => item.id == id)
      return temp
    },
    countDown() {
      let createTime = this.firstOrder?.create_time
      if (!createTime) return 0
      return (
        new Date(createTime).getTime() + 60 * 15 * 1000 - new Date().getTime()
      )
    },
    // 订单状态
    orderState() {
      let state = this.firstOrder?.state
      if (!state) return false
      return (state = state == 2)
    },
    // 显示收货地址
    orderAddress() {
      let info = this.firstOrder?.address
      if (!info || info == '{}') return {}
      return info
    },
    // 显示收货地址
    showAddress() {
      let info = this.orderAddress
      if (!info || info == '{}') return {}
      return Object.keys(info).length > 0
    },
    // 显示收货地址
    deliveryAddress() {
      let info = this.orderAddress
      return `${info.class_A}${info.class_B}${info.class_C}${info.class_D}`
    },
    // 显示是否全部退货
    isAllRefund() {
      let orderDeta = this.goodsOrderDeta
      if (!orderDeta.length) return false
      return orderDeta.every(v => v.state == 5)
    },
    orderDeta() {
      let data = this.goodsOrderDeta
      let obj = { haveAnAdd: [], noAddress: [] }
      for (let j = 0; j < data.length; j++) {
        let service = data[j].post_service
        if (service == 1 || service == 5) {
          obj.haveAnAdd.push(data[j])
        } else {
          obj.noAddress.push(data[j])
        }
      }
      return obj
    },
    noAddressOrder() {
      let data = this.orderDeta.noAddress?.[0]
      return data ? [data] : []
    },
    haveAnAddOrder() {
      let data = this.orderDeta.haveAnAdd?.[0]
      return data ? [data] : []
    }
  },
  methods: {
    async getGoodsOrderDetail(param) {
      const {
        data: { data }
      } = await goodsOrderDetailApi(param)
      let { brand } = this.brandInfo
      let base = `${this.baseUrl}/images/${brand}/library/`
      data.forEach((item, index) => {
        item.img = `${base}${item.images_kv}`
        if (item?.address && item?.address !== '{}') {
          item.address = JSON.parse(item.address)
        }
        if (
          (item?.post_service == 5 || item?.post_service == 1) &&
          item?.logistics_no?.length > 8
        ) {
          this.queryPostInfo2(item?.logistics_no, index)
          console.log('88')
        }
      })
      console.log(data)
      this.goodsOrderDeta = data
    },

    // 返回
    goBack(id) {
      uni.navigateTo({
        url: `/Shop/OrderAdmin`
      })
    },
    // 到商城页
    goShop() {
      uni.switchTab({
        url: `/pages/Shop/ShopAdmin`
      })
    },

    async queryPostInfo2(No, index) {
      let param = { waybillNo: `SF${No}` }
      const { data } = await fastPieceApi(param)
      if (data.apiResultData?.obj?.route[0]?.opCode == 80) {
        this.$set(this.PostInfo, index, true)
      }
    },

    onChange(e) {
      this.timeData = e
    },
    // 删除订单
    async callDeleteApi() {
      let v_id = this.firstOrder?.v_id
      const {
        data: { code, message }
      } = await groupMyGoodsDelApi({ v_id })
      if (code == 200) {
        this.delModal = false
        uni.$showMsg(`${message}`)
        // 到订单列表页
        uni.navigateTo({
          url: `/Shop/OrderAdmin?state=${2}`
        })
      }
    },
    finish() {
      // 返回上一级
      uni.navigateBack({
        delta: 1
      })
      // console.log('finish')
    },
    // 继续支付
    async clickPay() {
      let { v_id, price_paid } = this.firstOrder
      let temp = goodsOrder.map(item1 => item1.category_id1)
      let temp2 = [...new Set(temp)]
      this.orderType = []
      // 分类列表
      this.getShopTypeCateList(temp2)
      const [err, res] = await uni.login().catch(err => err)
      if (err || res.errMsg !== 'login:ok')
        return uni.$showMsg('获取code失败！')
      // 微信支付
      this.callUserPay(res.code, v_id, price_paid)
    },
    // 生成订单号，微信支付
    async callUserPay(code, vId, price) {
      let title = this.orderType.join(',')
      let { brand } = this.brandInfo
      let param = {
        code,
        price,
        title,
        brand,
        v_id: vId
      }
      const { data } = await userPayApi(param)
      if (data.code == 400) return uni.$showMsg(`${data.message}`)
      if (data.status != 200) return uni.$showMsg('支付订单创建失败！')
      console.log('支付', data)
      let { appId, timeStamp, nonceStr, signType, paySign } = data
      // 发起微信支付
      let payInfo = {
        provider: appId,
        // orderInfo: data.v_id,
        paySign,
        nonceStr,
        signType,
        timeStamp,
        orderInfo: vId,
        package: data.package,
      }
      const [err, succ] = await uni.requestPayment(payInfo)
      // 未完成支付
      if (err) {
        uni.$showMsg('订单未支付！')
      } else {
        uni.$showMsg('订单支付成功！')
        // 到订单列表页
        uni.redirectTo({
          url: `/Shop/OrderAdmin?state=${1}`
        })
      }
    },
    // 分类列表
    async getShopTypeCateList(temp2) {
      let { brand_id } = this.brandInfo
      const {
        data: { data, code }
      } = await getShopTypeCateListApi({
        brand_id,
        company_id: '1',
        state: '1'
      })
      if (code == 200) {
        for (let i = 0; i < temp2.length; i++) {
          for (let j = 0; j < data.length; j++) {
            if (temp2[i] == data[j].category_id1) {
              this.orderType.push(data[j].type_name)
              break
            }
          }
        }
      }
    },
    ...mapMutations(['changeGoodsState'])
  },
  onLoad(options) {
    let { v_id } = options
    let { uuid } = this.loginInfo
    this.getGoodsOrderDetail({ v_id, uuid })
    this.shareMixin.title = `订单详情`
    this.shareMixin.path = `/pages/Shop/ShopAdmin`
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/mixins.scss';

.container {
  // height: 100%;
  background-color: #f8f9f8;

  .pay {
    padding: 30rpx 0;

    &-title__box {
      padding-bottom: 30rpx;
      display: flex;
      justify-content: center;
      align-items: center;

      .pay-title {
        font-size: 24rpx;
      }
    }

    &-btn {
      display: flex;
      justify-content: center;
      align-items: center;

      &__cancel,
      &__toPay {
        width: 180rpx;
        line-height: 60rpx;
        font-size: 26rpx;
        border-radius: 35rpx;
        text-align: center;
        margin: 0 10rpx;
      }

      &__cancel {
        border: #999 1px solid;
        background-color: #fff;
      }

      &__toPay {
        color: #fafafa;
        border: #de4141 1px solid;
        background-color: #de4141;
      }
    }

    .time {
      align-items: center;

      &__item {
        font-size: 12px;
        text-align: center;
        color: #de4141;
      }
    }
  }
}

.card {
  width: 92%;
  padding: 30rpx;
  margin: 30rpx auto;
  background-color: #fff;
  border-radius: 15rpx;
  box-shadow: $theme-shadow;
}

.refund {
  font-size: 28rpx;
  line-height: 48rpx;
  color: #dd444c;
  font-weight: 600;
  text-align: center;
}

.total-prices {
  display: flex;
  justify-content: flex-end;
  align-content: center;
  font-size: 28rpx;
  line-height: 48rpx;
  color: #dd444c;
  font-weight: 600;

  .name {
    color: #222;
    margin-right: auto;
  }

  .value {
    // color: #999;
  }
}

.logistics_box {
  height: 65vh;
  overflow: auto;
}

.couponList-bottom {
  margin: 40rpx 0 90rpx 0;
  display: flex;
  justify-content: center;
  text-align: center;

  .couponList-bottom__btn {
    padding: 16rpx 22rpx;
    width: 260rpx;
    color: #fff;
    background: $theme-color;
    font-size: 30rpx;
    border-radius: 10rpx;
    border: 2rpx solid #dd444c;

    &:nth-last-child(1) {
      margin-left: 40rpx;
    }
  }
}
</style>
